﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class XluaEngine : MonoBehaviour
{
    // **************************  xlua *************************
    internal static XLua.LuaEnv _xlua = new XLua.LuaEnv();
    public static string LuaSrcPath
    {
        get {
            return Application.dataPath + "/xLuaScript";
        }
    }
    public static XLua.LuaEnv Lua
    {
        get {
            return _xlua;
        }
    }

    // **************************
    [SerializeField]
    private string mainFile = "main.lua";
    void Awake()
    {
#if UNITY_EDITOR
        Lua.AddLoader(this.onEditorLoader);
#endif
        if (AGame.EnableAB)
        {
            Lua.AddLoader(this.onAssetsbundleLoader);
        }
        Lua.DoString(string.Format(" require '{0}'", mainFile));
        Debug.Log(mainFile + " :  " + LuaSrcPath);
    }
    
    byte[] onEditorLoader(ref string luaFile)
    {
        if(Directory.Exists(LuaSrcPath))
        {
            if(luaFile.EndsWith(".lua"))
                luaFile = luaFile.Substring(0,luaFile.LastIndexOf('.'));
            luaFile = luaFile.Replace('.', '/')+ ".lua";
            string absPath = Path.Combine(LuaSrcPath, luaFile);
            if (File.Exists(absPath))
                return File.ReadAllBytes(absPath);
        }
        return null;
    }

    byte[] onAssetsbundleLoader(ref string luaFile)
    {
        if(Directory.Exists(LuaSrcPath))
        {
            if(luaFile.EndsWith(".lua"))
                luaFile = luaFile.Substring(0,luaFile.LastIndexOf('.'));
            luaFile = luaFile.Replace('.', '/')+ ".lua";
            string absPath = Path.Combine(LuaSrcPath, luaFile);
            if (File.Exists(absPath))
                return File.ReadAllBytes(absPath);
        }
        return null;
    }
    internal static float lastGCTime = 0;
    internal const float GCInterval = 1;//1 second 
    private void Update()
    {
        if (Time.time - lastGCTime> GCInterval)
        {
            Lua.Tick();
            lastGCTime = Time.time;
        }
    }
    void OnDestroy()
    {
        if (Lua != null)
        {
            _xlua.Dispose();
            _xlua = null;
        }
    }
    #if UNITY_EDITOR
    [SerializeField] private UnityEngine.Object reloadLua = null;
    [ContextMenu("Reload File")]
    void doReloadFile()
    {
        if (reloadLua != null)
        {
            string filePath = UnityEditor.AssetDatabase.GetAssetPath(reloadLua);
            filePath = Path.GetFullPath(filePath);
            byte[] bytes = File.ReadAllBytes(filePath);;
            Lua.DoString(bytes);
        }
    }
#endif
}
